from django import http
from django.http import JsonResponse
from django.views import View
from rest_framework.views import APIView

from goods.models import GoodsCategory, GoodsVisitCount


class DetailVisitView(APIView):
    """详情页分类商品访问量"""

    def post(self, request, category_id):
        """记录分类商品访问量"""
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code':400,
                                 'errmsg':'缺少必传参数'})

        # 获取今天的日期
        from django.utils import timezone
        today_date=timezone.localdate()
        try:
            # 查询今天该类别的商品的访问量
            counts_data = category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            # 如果该类别的商品在今天没有过访问记录，就新建一个访问记录
            counts_data = GoodsVisitCount()

        try:
            counts_data.category = category
            counts_data.count += 1
            counts_data.save()
        except Exception as e:
            return http.HttpResponseServerError('服务器异常')

        return http.JsonResponse({'code': 0, 'errmsg': 'OK'})